#include "timer.h"
#include "ui_timer.h"
#include "secondwindow.h" // 在 .cpp 中包含，而非 .h
#include <QCloseEvent>
#include <QMessageBox>

timer::timer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::timer)
{
    ui->setupUi(this);

    // === 手动连接所有按钮信号 ===
    connect(ui->starBt,   &QPushButton::clicked, this, &timer::startTimer);
    connect(ui->closeBt,  &QPushButton::clicked, this, &timer::stopTimer);
    connect(ui->resetBt,  &QPushButton::clicked, this, &timer::resetTimer);
    connect(ui->bitBt,    &QPushButton::clicked, this, &timer::recordLap);
    connect(ui->switchBt, &QPushButton::clicked, this, &timer::switchToDownloadPage);

    // 返回按钮
    connect(ui->backButton, &QPushButton::clicked, this, [this]() {
        emit backRequested();
        this->hide();
    });

    // 打点计时器
    connect(&timer_obj, &QTimer::timeout, this, &timer::timeout_slot);

    // 系统时间定时器（每秒更新）
    m_clockTimer = new QTimer(this);
    connect(m_clockTimer, &QTimer::timeout, this, &timer::updateTime);
    m_clockTimer->start(1000);
    updateTime(); // 初始化显示

    // 初始化打点时间为 0
    time.setHMS(0, 0, 0, 0);
    ui->showTime->setText("00:00:00:000");
}

timer::~timer()
{
    delete ui;
}

// --- 槽函数实现（无 on_ 前缀）---

void timer::startTimer()
{
    timer_obj.start(30);
}

void timer::stopTimer()
{
    timer_obj.stop();
}

void timer::resetTimer()
{
    timer_obj.stop();
    time.setHMS(0, 0, 0, 0);
    ui->showTime->setText("00:00:00:000");
    ui->bitTime->clear();
    recordCount = 0;
}

void timer::recordLap()
{
    recordCount++;
    QString line = QString("%1:").arg(recordCount);
    ui->bitTime->append(line);
    ui->bitTime->append(time.toString("hh:mm:ss:zzz"));
}

void timer::switchToDownloadPage()
{
    if (m_secondWindow) {
        m_secondWindow->deleteLater();
        m_secondWindow = nullptr;
    }

    m_secondWindow = new SecondWindow(nullptr);
    connect(m_secondWindow, &SecondWindow::backRequested, this, [this]() {
        this->show();
    });

    m_secondWindow->show();
    this->hide();
}

// --- 内部定时器槽函数 ---

void timer::timeout_slot()
{
    time = time.addMSecs(20);
    ui->showTime->setText(time.toString("hh:mm:ss.zzz"));
}

void timer::updateTime()
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QTimeZone beijingTimeZone("Asia/Shanghai");
    currentDateTime.setTimeZone(beijingTimeZone);
    QString beijingTimeStr = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
    ui->updateTime->setText(beijingTimeStr);
}

void timer::closeEvent(QCloseEvent *event)
{
    event->ignore();
    emit backRequested();
    this->hide();
}
